﻿using MESPro.Models.FunctionType;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
//using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Layout;

namespace MESPro.Controls
{
    /// <summary>
    /// RMDataGridViewEx
    /// </summary>
    [RMControl("表格", "RMDataGridView.ico")]
    public partial class RMDataGridView : UserControl, ICustomControl,ITitleControl
    {
        #region Public Constructors

        public RMDataGridView()
        {
            InitializeComponent();
            DoubleBuffered = true;
            this.dgv.CellClick += Dgv_CellClick;
        }
        public void DesignerInit()
        {
            this.dgv.Click += DataGridView1_Click;
            this.dgv.MouseDown += DataGridView1_MouseDown;
            this.dgv.MouseMove += DataGridView1_MouseMove;
      
        }
        #endregion Public Constructors

        #region 字段

        public Action<object, DataGridViewCellEventArgs>? RMRowSelect;
        private int pageSize = 20;
        private int pageIndex = 1;
        /// <summary>
        /// 总的数据源
        /// </summary>
        private DataTable? dataSourse;
        List<int> searchlist = new List<int>();

        #endregion 字段

        #region 属性

        /// <summary>
        /// 每页显示多少个
        /// </summary>
        
        [Browsable(false)]
        public int RMPageSize
        {
            get => pageSize; set
            {
                pageSize = value;
            }
        }

        /// <summary>
        /// 当前显示第几页,至少都是1
        /// </summary>
        [Browsable(false)]
        public int RMPageIndex
        {
            get => pageIndex; set
            {
                if (value <= 0)
                {
                    pageIndex = 1;
                }
                else
                {
                    pageIndex = value;
                }
            }
        }

        /// <summary>
        /// 总体的数据源
        /// </summary>
        [Browsable(false)]
        public DataTable? DataSourse
        {
            get => dataSourse; set
            {
                if (value != null)
                {
                    dataSourse = value;
                    RMPageIndex = 1;
                    this.totalCount.Text = dataSourse.Rows.Count.ToString();
                    this.dgv.DataSource = null;
                    this.dgv.DataSource = TableToPage(dataSourse, 0, RMPageSize);
                    this.dgv.Columns["Id"].Visible = false;
                }
            }
        }

        [Category("\t\t\t\t\t\t\t参数设置"), Description("暂时固定为dgv,请不要更改,后续会改造"), DisplayName("1.控件名"), Browsable(true),ReadOnly(true)]
        public new string Name { get => base.Name; set => base.Name = value; }

        //public override string Text
        //{
        //    get { return this.textBox1.Text; }
        //    set { this.textBox1.Text = value; }
        //}
        /// <summary>
        /// 存储过程
        /// </summary>
        [Category("\t\t\t\t\t\t\t参数设置"),
        Description("数据源的存储过程"),
        DisplayName("2.存储过程"),Browsable(false),
        TypeConverter(typeof(ExpandableObjectConverter)),
        Editor(typeof(PropertyReturnStoreProcedure), typeof(UITypeEditor))]
        [SugarColumn(IsJson = true)]
        public StoreProInfo StoredProcedure { get; set; } = new();

        [Category("\t\t\t\t\t\t\t参数设置"), Description("图标名字"), DisplayName("\t\t\t图标名字"),Browsable(false)]
        [Editor(typeof(PropertyReturnFileName),
typeof(System.Drawing.Design.UITypeEditor))]
        public string ImageName { get; set; } = "";

        [DisplayName("固定位置"), Description("固定位置"), Browsable(false)]
        public override AnchorStyles Anchor { get => base.Anchor; set => base.Anchor = value; }

        [DisplayName("定位"), Description("停靠"), Browsable(true)]
        public new Point Location { get => base.Location; set => base.Location = value; }

        [DisplayName("停靠位置"), Description("停靠位置"), Browsable(true)]
        public override DockStyle Dock { get => base.Dock; set => base.Dock = value; }

        [DisplayName("字体设置"), Description("字体设置"), Browsable(true)]
        public override Font Font { get => base.Font; set => base.Font = value; }
        [DisplayName("大小"), Description("控件大小,如果设置了停靠,大小将失效"), Browsable(true)]
        public new Size Size { get => base.Size; set => base.Size = value; }

        [DisplayName("背景色"), Description("背景色"), Browsable(true)]
        public override Color BackColor { get => base.BackColor; set => base.BackColor = value; }

        [DisplayName("字体颜色"), Description("字体颜色"), Browsable(true)]
        public override Color ForeColor { get => base.ForeColor; set => base.ForeColor = value; }

        [DisplayName("边框样式"), Description("边框样式"), Browsable(true)]
        public new BorderStyle BorderStyle { get => base.BorderStyle; set => base.BorderStyle = value; }

        //.....................................
        [Browsable(false)]
        public new bool AutoScroll { get => base.AutoScroll; set => base.AutoScroll = value; }

        [Browsable(false)]
        public new Size AutoScrollMargin { get => base.AutoScrollMargin; set => base.AutoScrollMargin = value; }

        [Browsable(false)]
        public new Size AutoScrollMinSize { get => base.AutoScrollMinSize; set => base.AutoScrollMinSize = value; }

        [Browsable(false)]
        public new AutoSizeMode AutoSizeMode { get => base.AutoSizeMode; set => base.AutoSizeMode = value; }

        [Browsable(false)]
        public new AutoValidate AutoValidate { get => base.AutoValidate; set => base.AutoValidate = value; }

        [Browsable(false)]
        public new Cursor Cursor { get => base.Cursor; set => base.Cursor = value; }

        [Browsable(false)]
        public new bool Visible { get => base.Visible; set => base.Visible = value; }

        [Browsable(false)]
        public new AccessibleRole AccessibleRole { get => base.AccessibleRole; set => base.AccessibleRole = value; }

        [Browsable(false)]
        public new string AccessibleName { get => base.AccessibleName; set => base.AccessibleName = value; }

        [Browsable(false)]
        public new string AccessibleDescription { get => base.AccessibleDescription; set => base.AccessibleDescription = value; }

        [Browsable(false)]
        public new bool TabStop { get => base.TabStop; set => base.TabStop = value; }

        [Browsable(false)]
        public new int TabIndex { get => base.TabIndex; set => base.TabIndex = value; }

        [Browsable(false)]
        public new bool Enabled { get => base.Enabled; set => base.Enabled = value; }

        [Browsable(false)]
        public new bool UseWaitCursor { get => base.UseWaitCursor; set => base.UseWaitCursor = value; }

        [Browsable(false)]
        public new ImeMode ImeMode { get => base.ImeMode; set => base.ImeMode = value; }

        [Browsable(false)]
        public override System.Drawing.Image BackgroundImage { get => base.BackgroundImage; set => base.BackgroundImage = value; }

        [Browsable(false)]
        public override RightToLeft RightToLeft { get => base.RightToLeft; set => base.RightToLeft = value; }

        [Browsable(false)]
        public override LayoutEngine LayoutEngine => base.LayoutEngine;

        [Browsable(false)]
        public new bool CausesValidation { get => base.CausesValidation; set => base.CausesValidation = value; }

        [Browsable(false)]
        public override bool AutoSize { get => base.AutoSize; set => base.AutoSize = value; }

        [Browsable(false)]
        public new Padding Margin { get => base.Margin; set => base.Margin = value; }

        [Browsable(false)]
        public new Padding Padding { get => base.Padding; set => base.Padding = value; }

        [Browsable(false)]
        public new Size MaximumSize { get => base.MaximumSize; set => base.MaximumSize = value; }

        [Browsable(false)]
        public new Size MinimumSize { get => base.MinimumSize; set => base.MinimumSize = value; }

        [Browsable(false)]
        public override bool AllowDrop { get => base.AllowDrop; set => base.AllowDrop = value; }

        [Browsable(false)]
        public override Point AutoScrollOffset { get => base.AutoScrollOffset; set => base.AutoScrollOffset = value; }

        [Browsable(false)]
        public override BindingContext BindingContext { get => base.BindingContext; set => base.BindingContext = value; }

        //[Browsable(false)]
        //protected override bool CanEnableIme => base.CanEnableIme;
        //[Browsable(false)]
        //public override ContextMenu ContextMenu { get => base.ContextMenu; set => base.ContextMenu = value; }
        [Browsable(false)]
        public override ImageLayout BackgroundImageLayout { get => base.BackgroundImageLayout; set => base.BackgroundImageLayout = value; }

        [Browsable(false)]
        public override ContextMenuStrip ContextMenuStrip { get => base.ContextMenuStrip; set => base.ContextMenuStrip = value; }

        //[Browsable(false)]
        //public override Cursor Cursor { get => base.Cursor; set => base.Cursor = value; }
        [Browsable(false)]
        public new ControlBindingsCollection DataBindings { get => base.DataBindings; }

        [Browsable(false)]
        public new object Tag { get => base.Tag; set => base.Tag = value; }

        [Browsable(false)]
        protected override ImeMode ImeModeBase { get => base.ImeModeBase; set => base.ImeModeBase = value; }

        [Browsable(false)]
        protected override bool CanRaiseEvents => base.CanRaiseEvents;

        #endregion 属性

        #region Public 方法

        /// <summary>
        /// 跳过多少个,选择多少个
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="from"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public static DataTable? TableToPage(DataTable? dt, int from, int pagesize)
        {
            if (dt == null) return null;

            DataTable pagedt = dt.Clone();

            var query = dt.AsEnumerable().Skip(from).Take(pagesize);
            foreach (DataRow item in query)
            {
                pagedt.Rows.Add(item.ItemArray);
            }
            return pagedt;
        }

        #endregion Public 方法

        #region Private 方法

        private static List<DataTable> DataTableSplite2(DataTable dt, int modcounts)
        {

            int counts = dt.Rows.Count / modcounts;  ///  取整数个数

            List<DataTable> list = new List<DataTable>();                                     ///  

            int index = 0;
            for (int i = 0; i < counts + 1; i++)
            {
                // list.Add(dt.AsEnumerable().Skip(index * modcounts).Take(modcounts).CopyToDataTable());

                index++;
            }
            return list;

        }

        private void Dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            RMRowSelect?.Invoke(sender, e);
        }
        private void DataGridView1_MouseMove(object sender, MouseEventArgs e)
        {
            base.OnMouseMove(e);
        }

        private void DataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            base.OnMouseDown(e);
        }

        private void DataGridView1_Click(object sender, EventArgs e)
        {
            base.OnClick(e);
        }
        private void 上一页(object sender, EventArgs e)
        {
            if (dataSourse != null)
            {

                RMPageIndex = RMPageIndex - 1;
                this.PageIndex.Text = RMPageIndex.ToString();
                this.dgv.DataSource = null;
                this.dgv.DataSource = TableToPage(dataSourse, RMPageSize * (RMPageIndex - 1), RMPageSize);
                this.dgv.Columns["Id"].Visible = false;

            }

        }

        private void 下一页(object sender, EventArgs e)
        {
            if (dataSourse != null)
            {
                RMPageIndex = RMPageIndex + 1;
                this.PageIndex.Text = RMPageIndex.ToString();
                this.dgv.DataSource = null;
                this.dgv.DataSource = TableToPage(dataSourse, RMPageSize * (RMPageIndex - 1), RMPageSize);
                this.dgv.Columns["Id"].Visible = false;
            }
        }
        private void PageSize_Leave(object sender, EventArgs e)
        {
            if (int.TryParse(this.PageSize.Text, out int size))
            {
                this.RMPageSize = size;
                this.dgv.DataSource = null;
                this.dgv.DataSource = TableToPage(dataSourse, RMPageSize * (RMPageIndex - 1), RMPageSize);
                this.dgv.Columns["Id"].Visible = false;
            }
        }

        private void PageSize_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (int.TryParse(this.PageSize.Text, out int size))
                {
                    this.RMPageSize = size;
                    this.dgv.DataSource = null;
                    this.dgv.DataSource = TableToPage(dataSourse, RMPageSize * (RMPageIndex - 1), RMPageSize);
                    this.dgv.Columns["Id"].Visible = false;
                }
            }
        }
        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                foreach (var item in searchlist)
                {
                    this.dgv.Rows[item].DefaultCellStyle.BackColor = Color.White;
                }
                searchlist.Clear();
                IEnumerable<DataGridViewRow> enumerableList = this.dgv.Rows.Cast<DataGridViewRow>();

                var res = enumerableList.Where((x) =>
                   {
                       foreach (DataGridViewCell item in x.Cells)
                       {
                           if (item.Value.ToString().Contains(this.search_txt.Text.ToString()))
                           {
                               return true;
                           }
                       }
                       return false;

                   }).ToList();
                this.dgv.DefaultCellStyle.BackColor = Color.White;
                this.dgv.RowsDefaultCellStyle.BackColor = Color.White;
                if (res.Count > 0)
                {
                    foreach (var item in res)
                    {
                        this.dgv.Rows[item.Index].DefaultCellStyle.BackColor = Color.Red;
                        searchlist.Add(item.Index);
                    }
                }
                //List<DataGridViewRow> list = (from item in enumerableList
                //                              where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0
                //                              select item).ToList();
                //if (list.Count > 0)
                //{
                //    // 查找匹配行高亮显示
                //    int matchedRowIndex = list[0].Index;
                //    this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Plum;
                //}

            }
        }

        #endregion Private 方法
    }
}
